﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ViewModels;
using BLL;

namespace LibraryMIS.UC
{
    public partial class BorrowBook : UserControl
    {
        UserVM vm;
        BorrowBLL borrow;
        DataSet ds;
        public BorrowBook()
        {
            InitializeComponent();
            vm = new UserVM();
            borrow = new BorrowBLL();
            ds = new DataSet();
        }

        private void GetStuPic(Guid stuid)
        {
            if (picboxUserPic != null)
                picboxUserPic.Image = null;//如果相片组件为非空，将相片进行清除

            var picObject = borrow.GetUserPhoto(stuid);//根据用户id获取相片
            if (picObject != null)
                picboxUserPic.Image = Image.FromStream(picObject);//将读出的相片绑定至目标picturebox组件Image属性
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            string stuno = this.txtStuNo.Text.Trim();//获取用户输入学号
            vm=borrow.GetUserInfoByStuNo(stuno);//
            if (vm != null)
            {
                this.txtName.Text = vm.Name;//将姓名绑定至对应组件
                this.txtClassName.Text = vm.ClassName;//将班级绑定至对应组件
                if (vm.Gender)
                    this.rbMale.Checked = true;//如果Gender为真，则男单选按钮被选定
                else
                    this.rbFemale.Checked = true;
                GetStuPic(vm.UserID);//加载用户相片
                ds = borrow.GetUserBorrowListByID(vm.UserID);//查找用户借阅记录

                if(ds.Tables[0].Rows.Count>0)
                    this.dgvBorrowList.DataSource = ds.Tables[0];

            }
        }

        private void btnBorrowing_Click(object sender, EventArgs e)
        {
            string bookid = this.txtBookID.Text.Trim();//获取用户输入索书号
            //如果用户没有输入索书号，提示并将光标定位在索书号输入框
            if(String.IsNullOrEmpty(bookid))
            {
                MessageBox.Show("请输入借阅书籍的索书号！", "系统提示");
                this.txtBookID.Focus();
            }
            else
            {
                bool result = borrow.InsertBorrowList(bookid, vm.UserID);//借书操作
                /// 如果借书操作返回为真值，借阅成功。弹窗提示，并重新刷新列表内容
                /// 如果借书操作返回为假值，借阅失败。弹窗提示
                if (result)
                {
                    MessageBox.Show("借书操作已成功完成！", "系统提示");
                    this.txtBookID.Clear();
                    this.txtBookID.Focus();

                    ds = borrow.GetUserBorrowListByID(vm.UserID);//查找用户借阅记录
                    if (ds.Tables[0].Rows.Count > 0)
                        this.dgvBorrowList.DataSource = ds.Tables[0];
                }
                else
                    MessageBox.Show("本书籍不可借阅，请查证后再次录入！", "系统提示");
            }

            
        }
    }
}
